package com.hksj.sftcm.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hksj.base.service.DefaultDeviceService;
import com.hksj.cbm.service.DeviceInstanceService;
import com.hksj.cbm.util.CellStyleStrategy;
import com.hksj.cbm.util.CustomCellWriteHandler;
import com.hksj.cbm.vo.SpaceModelVO;
import com.hksj.sftcm.dto.SftcmDeviceDTO;
import com.hksj.sftcm.mapper.SftcmDeviceMapper;
import com.hksj.sftcm.vo.SftcmDeviceVO;
import com.hksj.sftcm.vo.SftcmHistoryDeviceVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@Component
public class SftcmDeviceService {

    private static final Logger log = LoggerFactory.getLogger(SftcmDeviceService.class);

    @Autowired
    private SftcmDeviceMapper sftcmDeviceService;

    @Autowired
    private DeviceInstanceService deviceInstanceService;

    @Autowired
    private DefaultDeviceService defaultDeviceService;

    public IPage<SftcmDeviceVO> querySftcmDeviceByPage(SftcmDeviceDTO dto){
        IPage<SftcmDeviceVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        List<SftcmDeviceVO> list = sftcmDeviceService.querySftcmDeviceByPage(page,dto);
        // 如果查询结果为空，直接返回空的分页对象
        if (CollectionUtils.isEmpty(list)){
            return page;
        }
        // 从查询结果中提取非空路径信息
        List<String> pathList = list.stream()
                .map(SftcmDeviceVO::getPaths)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 将路径信息转换为UTF8格式
        Map<String, List<SpaceModelVO>> pathNameMap = deviceInstanceService.devicePathConvertToUTF8(pathList);
        // 如果路径信息非空，则将转换后的路径名称关联到查询结果中
        if (CollUtil.isNotEmpty(pathNameMap)) {
            list.forEach(vo -> {
                vo.setSpaceModelVOList(pathNameMap.get(vo.getPaths()));
            });
        }
        page.setRecords(list);
        return page;
    }


    public IPage<SftcmHistoryDeviceVO> querySftcmDeviceHistoryByPage(SftcmDeviceDTO dto) {
        Page<SftcmHistoryDeviceVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        // 初始化查询结果列表
        List<SftcmHistoryDeviceVO> energyHistoryList = new ArrayList<>();
        String tableName = "";
        Long total = 0L;
        //设备对应的超级表产品id和设备id实现对应
        try {
            tableName = defaultDeviceService.getTableName(dto.getProductId());
            if(dto.getPageNum()>0) {
                dto.setPageNum((dto.getPageNum() - 1)*dto.getPageSize());
            }
            energyHistoryList = sftcmDeviceService.querySftcmDeviceHistoryByPage(tableName, dto);
            total = sftcmDeviceService.querySftcmDeviceHistoryCount(tableName, dto);
        } catch (Exception e) {
            log.error("Error querying table {}: {}", tableName, e.getMessage(), e);
        }
        page.setRecords(energyHistoryList);
        page.setTotal(total);
        return page;
    }

    public void exportSftcmHistoryDeviceInfo(SftcmDeviceDTO dto, HttpServletResponse response) throws Exception {
        List<SftcmHistoryDeviceVO> energyHistoryList = new ArrayList<>();
        String tableName = "";
        List<List<String>> data = new ArrayList<>();
        try {
            tableName = defaultDeviceService.getTableName(dto.getProductId());
            dto.setPageNum(null);
            dto.setPageSize(null);
            energyHistoryList = sftcmDeviceService.querySftcmDeviceHistoryByPage(tableName, dto);
        } catch (Exception e) {
            log.error("Error querying table {}: {}", tableName, e.getMessage(), e);
        }
        if (!CollectionUtils.isEmpty(energyHistoryList)) {
            List<SftcmHistoryDeviceVO> finalEnergyHistoryList = energyHistoryList;
            data = IntStream.range(0, finalEnergyHistoryList.size())
                    .mapToObj(index -> {
                        SftcmHistoryDeviceVO energyHistory = finalEnergyHistoryList.get(index);
                        List<String> stringList = new ArrayList<>();
                        stringList.add(String.valueOf(index + 1));
                        stringList.add(energyHistory.getVal());
                        stringList.add(energyHistory.getTs().substring(0, 19));
                        return stringList;
                    })
                    .collect(Collectors.toList());
        }

        List<List<String>> header= new ArrayList<>();
        header.add(Collections.singletonList("序号"));
        header.add(Collections.singletonList("温度（℃）"));
        header.add(Collections.singletonList("上报时间"));

        String fileName = new StringBuffer()
                .append("设备历史数据表")
                .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date()))
                .append(".xlsx")
                .toString();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new CustomCellWriteHandler())
                .registerWriteHandler(new CellStyleStrategy(Collections.singletonList(0),new WriteCellStyle(), new WriteCellStyle()))
                .head(header)
                .sheet("sheet1")
                .doWrite(data);
    }
}
